package com.xiecong.aspect;

import com.xiecong.mapper.OperateLogMapper;
import com.xiecong.pojo.OperateLog;
import com.xiecong.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.xiecong.aspect.annotation.LogOperation)")
    public Object addLog(ProceedingJoinPoint pjp){
        log.info("开始记录日志");
        OperateLog operateLog = new OperateLog();
        long start = System.currentTimeMillis();
        Long end;
        // 调用原始方法
        Object result;
        try {
            // 获取操作时间
            operateLog.setOperateTime(LocalDateTime.now());
            // 获取返回值
            result = pjp.proceed();
            //把返回值转成json字符串
            operateLog.setReturnValue(result.toString());
            // 获取类名
            String className = pjp.getTarget().getClass().getName();
            operateLog.setClassName(className);
            // 获取方法名
            String methodName = pjp.getSignature().getName();
            operateLog.setMethodName(methodName);
            // 获取参数
            Object[] methodParams = pjp.getArgs();
            operateLog.setMethodParams(Arrays.toString(methodParams));
            // 获取操作员工id
            Integer operateEmpId = CurrentHolder.getCurrentEmp().getId();
            operateLog.setOperateEmpId(operateEmpId);
            // 获取操作员工名字
            String name = CurrentHolder.getCurrentEmp().getName();
            operateLog.setOperateEmpName(name);
            return result;
        } catch (Throwable e) {
            // 获取出现异常时的返回值
            operateLog.setReturnValue("出异常了！");
            return null;
        } finally {
            end = System.currentTimeMillis();
            operateLog.setCostTime(end-start);
            //保存日志到数据库
            operateLogMapper.insert(operateLog);
        }
    }
}
